package mao.thinkinjava.concurency.deadlock;

import java.util.Random;
import java.util.concurrent.TimeUnit;

public class Philosopher implements Runnable {

    private static Random random= new Random();
    static double panderFact;

    private int id;
    private ChopStick left;
    private ChopStick right;
    private void pause(boolean thinking) throws InterruptedException {
        if(thinking){
            TimeUnit.MICROSECONDS.sleep((int)(panderFact*random.nextInt(1000)));
        }else {
            TimeUnit.MICROSECONDS.sleep((int)((1-panderFact)*random.nextInt(1000)));
        }
    }

    public Philosopher(int id, ChopStick left, ChopStick right) {
        this.id = id;
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        try {
            while (true) {
                System.out.println(this + " " + "thinking");
                pause(true);
                System.out.println(this + " " + "is hungry");
                left.take();
                right.take();
                pause(false);
                left.drop();
                right.drop();
                System.out.println(this + " " + "had eat");
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }


    }

    @Override
    public String toString() {
        return "Philosopher{" +
                "id=" + id +
                '}';
    }
}
